package cn.iocoder.yudao.module.system.api.social;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserBindReqDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserRespDTO;
import cn.iocoder.yudao.module.system.api.social.dto.SocialUserUnbindReqDTO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserBindDO;
import cn.iocoder.yudao.module.system.dal.dataobject.social.SocialUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.social.SocialUserBindMapper;
import cn.iocoder.yudao.module.system.enums.social.SocialTypeEnum;
import cn.iocoder.yudao.module.system.service.social.SocialUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;

import java.util.Collections;
import java.util.List;

/**
 * 社交用户的 API 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class SocialUserApiImpl implements SocialUserApi {

    @Resource
    private SocialUserService socialUserService;

    @Resource
    private SocialUserBindMapper socialUserBindMapper;

    @Override
    public String bindSocialUser(SocialUserBindReqDTO reqDTO) {
        return socialUserService.bindSocialUser(reqDTO);
    }

    @Override
    public void unbindSocialUser(SocialUserUnbindReqDTO reqDTO) {
        socialUserService.unbindSocialUser(reqDTO.getUserId(), reqDTO.getUserType(),
                reqDTO.getSocialType(), reqDTO.getOpenid());
    }

    @Override
    public SocialUserRespDTO getSocialUser(Integer userType, Integer socialType, String code, String state) {
       return socialUserService.getSocialUser(userType, socialType, code, state);
    }

    @Override
    public SocialUserRespDTO getSocialUserByMemberUserId(Long userId) {
        List<SocialUserBindDO> socialUserBinds = socialUserBindMapper.selectList(new LambdaQueryWrapper<SocialUserBindDO>()
                .eq(SocialUserBindDO::getUserId, userId)
                .eq(SocialUserBindDO::getUserType, UserTypeEnum.MEMBER.getValue())
                .eq(SocialUserBindDO::getSocialType,SocialTypeEnum.WECHAT_MINI_APP.getType()));
        if (CollUtil.isEmpty(socialUserBinds)) {
            return null;
        }
        SocialUserBindDO socialUserBindDO = socialUserBinds.get(0);
        SocialUserDO socialUser = socialUserService.getSocialUser(socialUserBindDO.getSocialUserId());
        return new SocialUserRespDTO(socialUser.getOpenid(), userId);
    }

}
